package reflect;

import java.lang.reflect.Field;

/**
 * Created by User on 2017/11/16.
 */
public class 交换 {

    public static void main(String[] args) {
        Integer a = 1;
        Integer b = 2;

        swap(a, b);

        System.out.println("a="+a);
        System.out.println("b="+b);

    }

    public static void swap(Integer var1, Integer var2) {


        try {
            Field value = Integer.class.getDeclaredField("value");
            value.setAccessible(true);

            int tmp = var1;

            value.set(var1, var2);

            // tmp自动装箱成Integer  调用valueOf(int)
            // value.set(Object,Object)
            // value.set(var2, tmp);
            value.setInt(var2, tmp); // 不走自动装箱

            // IntegerCache里的值被更改了
            System.out.println(Integer.valueOf(1));
            System.out.println(Integer.valueOf(2));
            System.out.println((Integer)1);
            System.out.println((Integer)2);


        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }



}
